package cn.ddd.linktran.infrastructure.transform.gateway;

import cn.ddd.linktran.domain.domainobject.CompressionCodeDO;
import cn.ddd.linktran.domain.gateway.CompressionCodeGateWay;
import cn.ddd.linktran.infrastructure.transform.convertor.CompressionCodeConvertor;
import cn.ddd.linktran.infrastructure.transform.mapper.CompressionCodeMapper;
import cn.ddd.linktran.infrastructure.transform.po.CompressionCode;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class CompressionCodeGatewayImpl implements CompressionCodeGateWay {
    @Autowired
    private CompressionCodeMapper compressionCodeMapper;
    @Autowired
    private CompressionCodeConvertor compressionCodeConvertor;
    @Override
    public void insertCompressionCodeDO(CompressionCodeDO compressionCodeDO) {
        compressionCodeMapper.insert(compressionCodeConvertor.toPO(compressionCodeDO));
    }

    @Override
    public CompressionCodeDO getLatestAvailableCompressionCodeDO() {
        CompressionCode po = compressionCodeMapper.selectLatestAvailable();
        return po == null ? null : compressionCodeConvertor.toDO(po);
    }

    @Override
    public int updateByPrimaryKeySelective(CompressionCodeDO compressionCodeDO) {
        return compressionCodeMapper.updateById(compressionCodeConvertor.toPO(compressionCodeDO));
    }

    @Override
    public List<String> selectAllCompressionCode() {
        return null;
    }

    @Override
    public long countAllAvailableCodes() {
        // select count(*) where code_status=1 and deleted=0
        return compressionCodeMapper.selectCount(
                Wrappers.<CompressionCode>lambdaQuery()
                        .in(CompressionCode::getCodeStatus, (byte)1, (byte)2)
                        .eq(CompressionCode::getDeleted, (byte)0)
        );
    }

    @Override
    public List<String> fetchAvailableCodes(int page, int pageSize) {
        IPage<CompressionCode> p = compressionCodeMapper.selectPage(
                new Page<>(page, pageSize, false),
                Wrappers.<CompressionCode>lambdaQuery()
                        .select(CompressionCode::getCompressionCode)            // 仅取列更轻
                        .in(CompressionCode::getCodeStatus, (byte)1, (byte)2)   // 1/2 都收录
                        .eq(CompressionCode::getDeleted, (byte)0)
                        .orderByAsc(CompressionCode::getId)                     // 稳定分页
        );
        if (p.getRecords().isEmpty()) return Collections.emptyList();
        return p.getRecords().stream()
                .map(CompressionCode::getCompressionCode)
                .collect(Collectors.toList());
    }
}
